package com.yanwq.sayhi.controller.chat.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.yanwq.sayhi.MApplication;
import com.yanwq.sayhi.common.event.MessageEvent;
import com.yanwq.sayhi.controller.user.UserMgr;
import com.yanwq.sayhi.dao.bean.Chat;
import com.yanwq.sayhi.dao.bean.Message;
import com.yanwq.sayhi.widget.MToast;

import java.util.List;

import de.greenrobot.event.EventBus;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;

public class ChatService extends Service {
    private static ChatService service;
    private static Socket mSocket;
    private static boolean isConnected;
    private Handler mHandler;

    public ChatService() {
    }

    public static void start(Context context) {
        Intent intent = new Intent(context, ChatService.class);
        context.startService(intent);
    }

    public static void stop() {
        if (service != null) {
            service.stopSelf();
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        service = this;
        mHandler = new Handler(Looper.getMainLooper());
        MApplication application = (MApplication) getApplication();
        mSocket = application.getSocket();
        mSocket.on(Socket.EVENT_CONNECT, onConnect);
        mSocket.on(Socket.EVENT_DISCONNECT, onDisconnect);
        mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectError);
        mSocket.on(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
        mSocket.on("register", onRegister);
        mSocket.on("message", onMessage);
        mSocket.connect();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    public static void send(Message message) {
        if (mSocket != null) {
            mSocket.emit("message", JSON.toJSONString(message));
        } else {
            MToast.showShort("聊天服务未启动");
        }
    }

    private Emitter.Listener onRegister = new Emitter.Listener() {
        @Override
        public void call(final Object... args) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "注册成功", Toast.LENGTH_LONG).show();
                }
            });
        }
    };

    private Emitter.Listener onMessage = new Emitter.Listener() {
        @Override
        public void call(Object... args) {
            final Message message = JSON.parseObject((String) args[0], Message.class);
            message.save();
            List<Chat> chats = Chat.findWithQuery(Chat.class, "select * from chat where user=?", String.valueOf(message.getUser().getId()));

            if (chats.size() == 0) {
                Chat chat = new Chat();
                chat.setUser(message.getUser());
                chat.setLastContent(message.getContent());
                chat.setUpdateTime(System.currentTimeMillis());
                chat.save();
            } else {
                Chat chat = chats.get(0);
                chat.setLastContent(message.getContent());
                chat.setUpdateTime(System.currentTimeMillis());
            }

            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    mSocket.emit("received", JSON.toJSONString(message));
                    EventBus.getDefault().post(new MessageEvent(MessageEvent.NEW_MESSAGE));
                    Toast.makeText(getApplicationContext(),
                            "有新消息", Toast.LENGTH_LONG).show();
                }
            });
        }
    };

    private Emitter.Listener onConnect = new Emitter.Listener() {
        @Override
        public void call(Object... args) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    if (!isConnected) {
                        Message message = new Message();
                        message.setUserUuid(UserMgr.get().getUuid());
                        mSocket.emit("register", JSON.toJSONString(message));
                        Toast.makeText(getApplicationContext(),
                                "已连接", Toast.LENGTH_LONG).show();
                        isConnected = true;
                    }
                }
            });
        }
    };

    private Emitter.Listener onDisconnect = new Emitter.Listener() {
        @Override
        public void call(Object... args) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    isConnected = false;
                    Toast.makeText(getApplicationContext(),
                            "已断开", Toast.LENGTH_LONG).show();
                }
            });
        }
    };

    private Emitter.Listener onConnectError = new Emitter.Listener() {
        @Override
        public void call(Object... args) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "连接失败", Toast.LENGTH_LONG).show();
                }
            });
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        isConnected = false;
        mSocket.off(Socket.EVENT_CONNECT, onConnect);
        mSocket.off(Socket.EVENT_DISCONNECT, onDisconnect);
        mSocket.off(Socket.EVENT_CONNECT_ERROR, onConnectError);
        mSocket.off(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
        mSocket.off("register", onRegister);
        mSocket.off("message", onMessage);
        mSocket.disconnect();
    }
}
